<template>
  <div class="appointment-container">
    <div class="appointment-header">
      <PageHead class="page-title">
        <template #default>
          <div class="header-content">
            <el-icon class="header-icon"><Calendar /></el-icon>
            <span>挂号管理</span>
          </div>
        </template>
      </PageHead>
      <ShakeBtn
          type="primary"
          class="add-btn"
          @click="addRoleB"
      >
        <el-icon><Plus /></el-icon>
        新增挂号
      </ShakeBtn>
    </div>

    <div class="appointment-content">
<!--      <MyRow class="card-grid">
        <AppointCard
            v-for="a in appoint"
            :key="a.appointmentId"
            :a="a"
            @toSuc="toSuc(a.appointmentId)"
            class="appointment-card"
        />
      </MyRow>-->
      <ClientAppoint/>
    </div>

    <!-- 新增挂号模态框 -->
    <el-dialog
        v-model="modalView"
        :title="modalTit"
        draggable
        width="680px"
        class="appointment-dialog"
        :close-on-click-modal="false"
    >
      <el-form
          ref="myFormRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          label-position="top"
      >
        <div class="form-grid">
          <el-form-item label="就诊描述" prop="appointmentInfo">
            <el-input
                v-model="form.appointmentInfo"
                clearable
                placeholder="请输入就诊症状描述"
                type="textarea"
                :rows="3"
                show-word-limit
                maxlength="200"
            />
          </el-form-item>

          <el-form-item label="就诊时间" prop="appointmentDate" class="datetime-picker">
            <el-date-picker
                v-model="form.appointmentDate"
                :value-format="'YYYY-MM-DD'+'T'+'HH:mm:ss'"
                format="YYYY-MM-DD HH:mm"
                placeholder="请选择就诊时间"
                type="datetime"
                class="full-width"
                :disabled-date="disabledDate"
                :shortcuts="dateShortcuts"
            />
          </el-form-item>

          <el-form-item label="就诊主人" prop="clientId">
            <el-select
                v-model="form.clientId"
                filterable
                placeholder="请选择用户"
                @change="form.petId=null"
                class="full-width"
            >
              <el-option
                  v-for="d in clientNameL"
                  :key="d.clientId"
                  :label="d.clientName"
                  :value="d.clientId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="就诊宠物" prop="petId">
            <el-select
                v-model="form.petId"
                filterable
                placeholder="请选择宠物"
                class="full-width"
                :disabled="!form.clientId"
            >
              <el-option
                  v-for="d in petNameL"
                  :key="d.roleId"
                  :label="d.roleName"
                  :value="d.roleId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="就诊科室" prop="departmentId">
            <el-select
                v-model="form.departmentId"
                filterable
                placeholder="请选择科室"
                @change="form.doctorId=null"
                class="full-width"
            >
              <el-option
                  v-for="d in departmentNameL"
                  :key="d.roleId"
                  :label="d.roleName"
                  :value="d.roleId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="接诊医生" prop="doctorId">
            <el-select
                v-model="form.doctorId"
                filterable
                placeholder="请选择医生"
                class="full-width"
                :disabled="!form.departmentId"
            >
              <el-option
                  v-for="d in doctorNameL"
                  :key="d.roleId"
                  :label="d.roleName"
                  :value="d.roleId"
              />
            </el-select>
          </el-form-item>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="modalView = false" size="large">取消</el-button>
          <el-button
              type="primary"
              @click="formSubmit"
              size="large"
              :loading="submitLoading"
          >
            确认提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import PageHead from "@/components/row/PageHead.vue";
import MyRow from "@/components/row/MyRow.vue";
import {AppointDto2} from "@/model/DO/AppointDto2";
import AppointCard from "@/components/card/AppointCard.vue";
import ShakeBtn from "@/components/button/ShakeBtn.vue";
import {reqDealAppoint, reqDoctorAddAppoint, reqDoctorAppoint, reqDoctorNameByDepartId} from "@/request/DoctorApi";
import {nextTick, onMounted, reactive, ref, watch} from "vue";
import {NameDo} from "@/model/DO/NameDo";
import {Appoint, exampleAppoint} from "@/model/entiy/Appoint";
import {ElMessage, FormInstance, FormRules} from "element-plus";
import {reqPetNameByClientId} from "@/request/PetApi";
import {reqClientNameHavePet} from "@/request/ClientApi";
import {reqDepartNameHaveDoctor} from "@/request/DepartApi";
import {reqLoginUser} from "@/request/PowerApi";
import { Calendar, Plus } from '@element-plus/icons-vue'
import ClientAppoint from "@/views/reception/clientAppoint.vue";

// 新增状态变量
const submitLoading = ref(false)
const dateShortcuts = [
  {
    text: '今天',
    value: new Date(),
  },
  {
    text: '明天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: '一周后',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
      return date
    },
  },
]

const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
}
const appoint = ref<AppointDto2[]>([])
// 修改这部分代码
onMounted(() => {
  reqLoginUser().then((res: any) => {
    // 将单个用户对象转换为数组格式
    clientNameL.value = [{
      clientId: res.clientId,
      clientName: res.clientName
    }]
    form.value.clientId = res.clientId
  })
  nextTick()
})

// 查询订单
const queryAppoint = () => {
  reqDoctorAppoint().then(res => {
    appoint.value = res
  })
}

// 处理挂号
const toSuc = (id: number) => {
  reqDealAppoint({appointId: id, isSuc: true}).then(res => {
    if (res.code === 1) queryAppoint()
  })
}
const doctorNameL = ref<NameDo[]>([])
const departmentNameL = ref<NameDo[]>([])
// 表单的数据
const modalView = ref(false)
const clientNameL = ref([] as any) // 下拉框用户名
const petNameL = ref<NameDo[]>([])
const form = ref<Appoint>(exampleAppoint()) // 空的默认值
const myFormRef = ref<FormInstance>()
/**
 ┌───────────────────────────────────┐
 │=============新增修改按钮============│
 └───────────────────────────────────┘
 */
// 模态框

const modalTit = ref<"新增挂号" | "修改挂号">("修改挂号")
// 新增时展示模态框
const addRoleB = (): void => {
  form.value = exampleAppoint()
  myFormRef.value?.resetFields()
/*  reqClientNameHavePet(null).then(res => {
    clientNameL.value = res;
  })*/
  reqDepartNameHaveDoctor(null).then(res => {
    departmentNameL.value = res;
  })
  modalTit.value = "新增挂号"
  modalView.value = true
}
// 修改时展示模态框
const showDialog = (row: Appoint) => {
  myFormRef.value?.clearValidate()
  // ===这样挨个赋值比较好===
  // 可以避免表单内容变化，表格内容也同步变化
  // 但感觉不如直接查询单个
  form.value.appointmentId = row.appointmentId
  form.value.appointmentDate = row.appointmentDate
  form.value.appointmentInfo = row.appointmentInfo
  form.value.clientId = row.clientId
  form.value.petId = row.petId
  form.value.departmentId = row.departmentId
  form.value.doctorId = row.doctorId
  // ===赋值完成===
/*  reqClientNameHavePet(form.value.clientId).then(res => {
    clientNameL.value = res;
  })*/
  reqDepartNameHaveDoctor(form.value.departmentId).then(res => {
    departmentNameL.value = res;
  })
  modalView.value = true
  modalTit.value = "修改挂号"
}
// 新增
/*const addRoleB = (): void => {
  form.value = exampleAppoint()
  myFormRef.value?.resetFields()
  modalView.value = true
}*/
// 校验表单并提交
const formSubmit = async (): Promise<void> => {
  await myFormRef.value?.validate((valid: boolean): void => {
    if (valid) {
      // 校验通过，提交
      modalView.value = false
      reqDoctorAddAppoint(form.value).then(res => {
        if (res.code === 1) {
          ElMessage.success('挂号成功！！！')
        }

          /*queryAppoint()*/
      })
    }
  })
}
// 表单校验规则
const rules = reactive<FormRules>({
  "appointmentInfo": [
    {required: true, message: '请输入描述', trigger: 'blur'},
  ],
  "appointmentDate": [
    {required: true, message: '请输入日期', trigger: 'blur'},
  ],
  "clientId": [
    {required: true, message: '请选择用户', trigger: 'blur'},
  ],
  "petId": [
    {required: true, message: '请选择宠物', trigger: 'blur'},
  ],
})

// 在用户改变时，查询宠物名
watch(() => form.value.clientId, (newValue): void => {
  if (newValue == 0 || newValue == null) return;
  reqPetNameByClientId(newValue, <number>form.value.petId).then(res => {
    petNameL.value = res
  })
})
// 在科室改变时，查询医生名
watch(() => form.value.departmentId, (newValue): void => {
  if (newValue == 0 || newValue == null) return;
  reqDoctorNameByDepartId(newValue).then(res => {
    doctorNameL.value = res
  })
})
</script>

<style scoped>
.appointment-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.appointment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 12px;
}

.appointment-header .header-content {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.appointment-header .header-content {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #d81b60; /* 深粉色文字 */
}

.appointment-header .header-content .header-icon {
  margin-right: 10px;
  font-size: 22px;
  color: #ff4081; /* 亮粉色图标 */
}

.add-btn {
  padding: 10px 20px;
  border-radius: 6px;
  font-weight: 500;
  background-color: #ff4081; /* 粉色按钮背景 */
  border-color: #ff4081;
  color: white; /* 白色文字 */
  transition: all 0.3s ease;
}

.add-btn:hover {
  background-color: #f50057; /* 深一点的粉色悬停效果 */
  border-color: #f50057;
  transform: translateY(-2px);
}

.add-btn .el-icon {
  margin-right: 6px;
  color: white; /* 白色图标 */
}

.appointment-content {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 1px 4px rgba(216, 27, 96, 0.12); /* 粉色阴影 */
  border: 1px solid #ffebee; /* 浅粉色边框 */
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 16px;
}

.appointment-card {
  transition: all 0.3s ease;
  border-radius: 8px;
  overflow: hidden;
}

.appointment-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.appointment-dialog .el-dialog__header {
  border-bottom: 1px solid #eee;
  margin-right: 0;
}

.appointment-dialog .el-dialog__body {
  padding: 20px 25px;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.full-width {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 16px 24px;
  border-top: 1px solid #eee;
}

.dialog-footer .el-button {
  min-width: 100px;
}

.datetime-picker .el-input__wrapper {
  width: 100%;
}

@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }

  .appointment-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .add-btn {
    width: 100%;
    justify-content: center;
  }
}
</style>
